/*
 * @Description: 表单校验-第一个Drawer
 * @Autor: gufuyan
 * @Date: 2021-11-15 10:30:41
 * @lastModifiedBy: gufuyan
 * @LastEditTime: 2021-12-03 15:24:47
 * @lastModifiedContent:
 */

import React, { useState, useEffect } from 'react';
import { Drawer, Button, Popconfirm } from 'antd';
import { PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { useModel } from 'umi';
import { intl } from '../FormAttributes';
import AddValidationRule from './AddValidationRule';
import type { ValidatorsType } from '@/models/drag';
import type { IValidationRuleProps, EditRule, Rely } from './data';
import styles from './index.less';

const ValidationRule: React.FC<IValidationRuleProps> = (props) => {
  const { type, field } = props;
  // 配置全局信息
  const drag = useModel('drag');
  // 提交校验配置
  const dragValidators: ValidatorsType[] = [...drag.config.validators];
  const [childrenDrawer, setChildrenDrawer] = useState(false);
  // 当前配置的公式校验
  const [validators, setValidators] = useState<ValidatorsType[]>([]);
  // 组件公式联动数据
  const [rely, setRely] = useState<Rely>();
  // 待使用
  const [layoutField, setLayoutField] = useState({});
  // 编辑数据
  const [editType, setEditType] = useState('');
  const [editRule, setEditRule] = useState<EditRule>({});

  useEffect(() => {
    // 初始化设置layout组件信息
    const newLayoutField = {};
    drag.config?.contentItem?.forEach(
      (el: { id: string | number; title: string; name: string; field: string }) => {
        newLayoutField[el.id] = {
          label: el.title,
          value: el.id,
          type: el.name,
          fieldName: el.field,
        };
      },
    );
    setLayoutField(newLayoutField);
  }, [drag]);

  useEffect(() => {
    // 点击的是组价公式联动
    if (!props.visible) return;
    if (type === 'component') {
      if (props.field?.rely?.formula) {
        setRely(props.field?.rely);
        setValidators([
          {
            formula: props.field?.rely?.formula?.formula,
            remind: '组件属性公式配置',
            tempId: new Date().getTime(),
          },
        ]);
      } else {
        setRely({
          formula: {
            formula: 'null',
            text: '公式',
            type: 'formula',
          },
          widgets: [],
        });
      }
    } else {
      // 点击表单提交校验
      setValidators(dragValidators);
    }
  }, [props.visible]);

  /**
   * 关闭弹出框，提交数据
   */
  const onSubmit = () => {
    // 公式联动
    if (type === 'component' && validators.length) {
      const newRely: any = rely;
      newRely.formula.formula = validators[0].formula;
      const widgets: string[] = [];
      const str = validators[0].formula.split('$');
      str.forEach((item) => {
        if (item.includes('#')) {
          const indexOf = item.indexOf('#');
          widgets.push(item.slice(0, indexOf));
        }
      });
      newRely.widgets = widgets;
      props.handleClose(newRely);
    } else {
      // 提交校验
      drag.fn.setValidators(validators);
      props.handleClose();
    }
  };

  /**
   * 添加公式关闭回调
   */
  const addRuleClose = (data: { formula: string; remind: string; tempId: string | number }) => {
    if (data) {
      // 提交校验
      if (type === 'form') {
        const newvalidators: ValidatorsType[] = validators;
        if (editType === 'add') {
          newvalidators.push(data);
        } else {
          newvalidators.forEach((item: ValidatorsType) => {
            if (item.tempId === editRule?.tempId) {
              item.formula = data.formula;
              item.remind = data.remind;
            }
          });
        }
        setValidators(newvalidators);
      } else {
        // 公式联动
        setValidators([data]);
      }
    }
    setChildrenDrawer(false);
  };

  return (
    <Drawer
      title={
        <div>
          {type === 'component' ? `公式编辑：${field.title}` : intl('drag.validate.title')}
          <label className={styles.tip}>（{intl('drag.validate.tip')}）</label>
        </div>
      }
      key="validate"
      placement="left"
      width={500}
      closable={false}
      visible={props.visible}
      style={{
        left: childrenDrawer ? 1000 - 180 : 0,
      }}
      footer={
        <div className={styles.footer}>
          <Button className={styles.btn} onClick={onSubmit}>
            {intl('drag.close')}
          </Button>
        </div>
      }
    >
      {/* 表单提交校验提示 */}
      {type === 'form' && (
        <p>
          {intl('drag.submit.verify.tip')}
          <a>{intl('drag.learn.more')}</a>
        </p>
      )}
      <Button
        type="primary"
        icon={<PlusOutlined />}
        onClick={() => {
          setEditType('add');
          setEditRule({});
          setChildrenDrawer(true);
        }}
      >
        {type === 'form' ? intl('drag.submit.verify.btn') : intl('drag.fx.btn')}
      </Button>

      {/* 公式配置配置列表 */}
      {validators?.map((item, idx) => {
        return (
          <div key={item.tempId} className={styles.showItem}>
            <div>
              <label className={styles.title}>
                {type === 'form' ? '校验公式：' : '计算逻辑：'}
              </label>
              <div>{item.formula}</div>
            </div>
            {type === 'form' && (
              <div>
                <label className={styles.title}>错误提示：</label>
                <label>{item.remind}</label>
              </div>
            )}
            <div className={styles.operate}>
              <div
                className={styles.edit}
                onClick={() => {
                  setEditType('edit');
                  setEditRule(item);
                  setChildrenDrawer(true);
                }}
              >
                {intl('drag.edit')}
              </div>
              <Popconfirm
                title="请确认是否删除该校验规则？"
                icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
                onConfirm={() => {
                  const newData = [...validators];
                  newData.splice(idx, 1);
                  setValidators(newData);
                }}
              >
                <a className={styles.delete}>{intl('drag.delete')}</a>
              </Popconfirm>
            </div>
          </div>
        );
      })}

      {/* 添加公式 */}
      <AddValidationRule
        type={type}
        editType={editType}
        editRule={editRule}
        visible={childrenDrawer}
        onClose={addRuleClose}
        field={props.field}
      />
    </Drawer>
  );
};

export default ValidationRule;
